package radio;


import http.Request;
import http.Response;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by zzf on 2017/4/26.
 */
public class Notifier {
    private static List<ServerListener> listeners = null;
    private static Notifier instance = null;

    private Notifier() {
        listeners = new LinkedList<>();
    }

    /**
     * 获取事件触发器
     * @return 返回事件触发器
     */
    public static synchronized Notifier getNotifier() {
        if (instance == null) {
            instance = new Notifier();
            return instance;
        }
        else return instance;
    }

    /**
     * 添加事件监听器
     * @param listener 监听器
     */
    public void addListener(ServerListener listener) {
        synchronized (listeners) {
            if (!listeners.contains(listener))
                listeners.add(listener);
        }
    }

    public void notifierAccepted() {
        for (ServerListener sListener :
                listeners) {
            sListener.onAccept();
        }
    }

    public void notifierRead(Request request) {
        for (ServerListener sListener :
                listeners) {
            sListener.onRead(request);
        }
    }


    public void notifierWrite(Response response) throws IOException {
        for (ServerListener sListener :
                listeners) {
            sListener.onWrite(response);
        }
    }
}
